﻿using AutoMapper;
using Enter.Dashboard.Api.Dtoes;
using Enter.Dashboard.Api.Dtoes.Requests;
using Enter.Dashboard.Api.Dtoes.Responses;
using Enter.Dashboard.Api.Entities;
using Enter.Dashboard.Api.Filters;
using Enter.Utils;
using FreeSql;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Enter.Dashboard.Api.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    [Authorization]
    public class CaseController : BaseController
    {
        public CaseController(ILogger<CaseController> logger, IDistributedCache cache, IFreeSql fsql, IMapper mapper) : base(logger, cache, fsql, mapper)
        {
            //_mapper = mapper;
        }

        [HttpGet]
        public ResponseData<List<ColumnProperty>> Columns()
        {
            var columns =  ComposeExtend.Headers<CaseListResponse>();           
            return ResponseData<List<ColumnProperty>>.OK(_mapper.Map<List<ColumnProperty>>(columns));
        }

        [HttpPost]
        public ResponseData<PageResponse<CaseListResponse>> List([FromBody]PageSearchRequest<CaseListRequest> request)
        {
            var _select = SearchList(request.Search);
            var list = _select.OrderByDescending(t => t.Id).Count(out var total).Page(request.PageIndex, request.PageSize).ToList();

            var data = _mapper.Map<List<CaseListResponse>>(list);
            var result = new PageResponse<CaseListResponse>(total, data);

            return ResponseData<PageResponse<CaseListResponse>>.OK(result);
        }

        private ISelect<Archive> SearchList(CaseListRequest model)
        {
            var _select = _fsql.Select<Archive>();
            if (model == null) 
            {
                return _select;
            }
            if (model.TableId > 0)
            {
                _select = _fsql.Select<Archive>().InnerJoin("ArchiveTableMap b on b.ArchiveId = a.Id and b.TableId = @TableId", new { TableId = model.TableId });
            }
            _select = _select.WhereIf(model.Id > 0, t => t.Id == model.Id)
             .WhereIf(!string.IsNullOrWhiteSpace(model.BusinessNo), t => t.BusinessNo == model.BusinessNo)
             .WhereIf(!string.IsNullOrWhiteSpace(model.ContractNo), t => t.ContractNo.Contains(model.ContractNo))
             .WhereIf(!string.IsNullOrWhiteSpace(model.CustomerID), t => t.CustomerID.Contains(model.CustomerID));

            var dynamicWhere = false;
            DynamicFilterInfo info = new DynamicFilterInfo();
            info.Logic = DynamicFilterLogic.And;
            info.Filters = new List<DynamicFilterInfo>();
            if (!string.IsNullOrWhiteSpace(model.SearchStringField) && !string.IsNullOrWhiteSpace(model.SearchStringValue))
            {
                info.Filters.Add(new DynamicFilterInfo
                {
                    Field = model.SearchStringField.Trim(),
                    Value = model.SearchStringValue,
                    Operator = model.SearchStringOperator,
                });
                dynamicWhere = true;
            }
            if (!string.IsNullOrWhiteSpace(model.SearchEnumField) && !string.IsNullOrWhiteSpace(model.SearchEnumValue) && model.SearchEnumValue != "0")
            {
                info.Filters.Add(new DynamicFilterInfo
                {
                    Field = model.SearchEnumField.Trim(),
                    Value = model.SearchEnumValue,
                    Operator = DynamicFilterOperator.Eq,
                });
                dynamicWhere = true;
            }
            if (!string.IsNullOrWhiteSpace(model.SearchDateField) && !string.IsNullOrWhiteSpace(model.SearchDateValue))
            {
                info.Filters.Add(new DynamicFilterInfo
                {
                    Field = model.SearchDateField.Trim(),
                    Value = model.SearchDateValue.Split(" - "),
                    Operator = DynamicFilterOperator.DateRange,
                });
                dynamicWhere = true;
            }
            if (dynamicWhere)
            {
                _select.WhereDynamicFilter(info);
            }
            if (!string.IsNullOrWhiteSpace(model.FullText))
            {
                //DynamicFilterInfo
                _select.Where(t => t.ContractNo.Contains(model.FullText) || t.BatchNo.Contains(model.FullText));
            }
            return _select;
        }

        //// GET api/<CaseController>/5
        //[HttpGet("{id}")]
        //public string Get(int id)
        //{
        //    return "value";
        //}

        //// POST api/<CaseController>
        //[HttpPost]
        //public void Post([FromBody] string value)
        //{
        //}

        //// PUT api/<CaseController>/5
        //[HttpPut("{id}")]
        //public void Put(int id, [FromBody] string value)
        //{
        //}

        //// DELETE api/<CaseController>/5
        //[HttpDelete("{id}")]
        //public void Delete(int id)
        //{
        //}
    }
}
